
import 'dart:ui';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:provider/provider.dart';
import 'package:ysy_flutter_mvvm_yuanxuan/bean/detail/AddCartEntity.dart';
import 'package:ysy_flutter_mvvm_yuanxuan/bean/detail/GoodsDetailsBean.dart';
import 'package:ysy_flutter_mvvm_yuanxuan/helper/AccidentTreatment.dart';
import 'package:ysy_flutter_mvvm_yuanxuan/helper/ImageHelper.dart';
import 'package:ysy_flutter_mvvm_yuanxuan/helper/RouteHelper.dart';
import 'package:ysy_flutter_mvvm_yuanxuan/helper/ViewHelper.dart';
import 'package:ysy_flutter_mvvm_yuanxuan/widget/ButtonSheet.dart';

import 'DetailsVM.dart';

//商品详情
class GoodsDetails extends StatelessWidget {
 late GoodsDetailsVM goodsDetailsVM ;

  GoodsDetails(){
    goodsDetailsVM = GoodsDetailsVM();
  }

  @override
  Widget build(BuildContext context) {
    var goodsDetailsId = getGoodsDetailsArguments(context);
    if(goodsDetailsId==null || goodsDetailsId.isEmpty){
      showCenterToast("商品不存在！");
      Navigator.of(context).pop();
    }
    return ChangeNotifierProvider(
      create: (BuildContext context){ return goodsDetailsVM;},
      child: Selector(
        selector: (BuildContext context, GoodsDetailsVM vm) {
          return vm.detailsBean;
        },
        builder: (BuildContext context,GoodsDetailsBean? value, Widget? child) {
          return BodyWidget(goodsDetailsVM,value,goodsDetailsId!);
        },
      ),
    );
  }

}

class BodyWidget extends StatefulWidget {

  final GoodsDetailsVM detailsVM;
  final String goodsDetailsId;
  final GoodsDetailsBean? value;

  BodyWidget(this.detailsVM,this.value,this.goodsDetailsId);

  @override
  _BodyWidgetState createState() => _BodyWidgetState();

}

class _BodyWidgetState extends State<BodyWidget> {

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance?.addPostFrameCallback((timeStamp) {
       widget.detailsVM.getGoodsDetails(goodsId: widget.goodsDetailsId);
    });
  }

  void addCart(){
    var list = widget.value?.skuStockList;
    if(list==null || list.isEmpty){
      showBottomToast("该商品没有sku");
      return;
    }
    SkuStockList? skuStock = list[0];
    int quantity=1;
    String productType="PROTYPE0001";
    if(skuStock.isOrder==1){
      productType="PROTYPE0002";
      quantity=(skuStock.stock??0)>0?(skuStock.stock!+1):1;
    }else if((skuStock.stock??0)>0){
      productType="PROTYPE0001";
    }else{
      return;
    }
    Product? product = widget.value?.product;
    if(product==null){
      showBottomToast("商品异常！");
      return;
    }
    widget.detailsVM.onAddCart(addCartEntity: AddCartEntity(skuStock, product, quantity, productType));
  }


  @override
  Widget build(BuildContext context) {
    List<ProductAttributeValueList> list=widget.value?.productAttributeValueList??[];
    var scSize = MediaQuery.of(context).size;
    var gnHeight = calculateHeight(72.sp, list.length,2);
    return Scaffold(
      body: Container(
        alignment: Alignment.topCenter,
        child: Stack(
          alignment: Alignment.topCenter,
          children: [
            //图片展示
            Container(
              alignment: Alignment.bottomCenter,
              height: scSize.height-78.h,
              child: Stack(
                children: [
                  assetImage(widget.value?.product?.pic??"",width:double.infinity,height:double.infinity,fit: BoxFit.fill),
                  BackdropFilter(
                    filter: ImageFilter.blur(sigmaX: 3, sigmaY: 3),
                    child: Container(
                      color: Colors.black.withOpacity(0.5),
                    ),
                  ),
                  PageView.builder(
                    itemCount:widget.value?.product?.albumPics?.split(",")?.length??0 ,
                    itemBuilder: (BuildContext context, int index) {
                      return assetImage(widget.value?.product?.albumPics?.split(",")?[index]??"",alignment: Alignment.center,);
                    },
                  ),
                ],
              ),
            ),
            //标题栏功能
            Container(alignment: Alignment.topCenter,
                child: DufTitleBar(
                  backWidget:GoodsTitleFunWidget("ic_arrow_left_black_bold.png"),
                  more: IntrinsicWidth(
                    child: Row(mainAxisAlignment:MainAxisAlignment.end,children: [
                      GoodsTitleFunWidget("ic_goods_shopping_write.png",onTap:(){toCartList(context);},),
                      Padding(padding: EdgeInsets.fromLTRB(0, 0, 20.w, 0)),
                      GoodsTitleFunWidget("ic_title_share_white.png",onTap:(){showCenterToast("该功能未开放");},),
                    ],),
                  ),
                )
            ),
            //右边功能栏
            Container(
              height: double.infinity,
              alignment: Alignment.centerRight,
              padding: EdgeInsets.fromLTRB(0, 0, 12.sp, 0),
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                crossAxisAlignment: CrossAxisAlignment.center,
                children: [
                  Container(
                    width: 40.sp,
                    height: 40.sp,
                    margin: EdgeInsets.fromLTRB(0, 0, 0, 30.h),
                    child:InkWell(
                      onTap: (){showCenterToast("这是去店铺主页的，但是我不想做！");},
                      child: ClipRRect(
                        // radius: 20.sp,
                        borderRadius: BorderRadius.all(Radius.circular(20.sp)),
                        child: assetImage(widget.value?.tsysStoreInfo?.logoPath??"",fit: BoxFit.fill,width: 20.sp,height: 20.sp),
                      ),
                    ) ,
                  ),
                  Selector(
                    builder: (BuildContext context, value, Widget? child) {
                        return GoodsFunWidget("喜欢", value==1?"ic_find_comment_like_yes.png":"ic_goods_like.png",onTap: (){
                          widget.detailsVM.onGoodsDetailsLike(goodsId: widget.goodsDetailsId);
                        },);
                    },
                    selector: (BuildContext , GoodsDetailsVM detailsVM) {
                       return detailsVM.like;
                    },
                  ),
                  Selector(
                    builder: (BuildContext context, value, Widget? child) {
                      return GoodsFunWidget("收藏", value==1?"ic_my_goods_collection.png":"ic_goods_collection.png",onTap: (){
                        widget.detailsVM.onGoodsDetailsCollection(goodsId: widget.goodsDetailsId);
                      },);
                    },
                    selector: (BuildContext , GoodsDetailsVM detailsVM) {
                      return detailsVM.collection;
                    },
                  ),
                  GoodsFunWidget("评价", "ic_find_comment.png",onTap: (){showCenterToast("评价被奇怪的人吃了！看不到");},),
                  GoodsFunWidget("", "ic_goods_addshopping.png",onTap: (){
                    addCart();
                  },),
                ],
              ),
            ),
            //商品信息展示
            ButtomSheet(
              decoration: ShapeDecoration(color: Colors.white, shape: RoundedRectangleBorder(borderRadius: BorderRadius.vertical(top: Radius.circular(16.r),bottom: Radius.zero)),),
              maxSheetHeight: 610.sp,minSheetHeight: 120.h,maxChildScrollDistance: gnHeight,headHeight: 290.sp,
              head: InfoHeadWidget(widget.value),
              child:Container(
                padding: EdgeInsets.fromLTRB(21.w, 0.h, 21.w, 0.h),
                alignment: Alignment.topCenter,
                height: gnHeight,
                color: Colors.white,
                child:GridView.builder(
                  padding: EdgeInsets.zero,
                  itemCount: list.length,
                  physics: NeverScrollableScrollPhysics(),
                  gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(crossAxisCount: 2,crossAxisSpacing: 12.sp,mainAxisSpacing: 15.sp,mainAxisExtent: 52.sp),
                  itemBuilder: (BuildContext context, int index) {
                    ProductAttributeValueList? productAttribute = list[index];
                    return BasisInfoItem(productAttribute);
                  },) ,
              ),
            )
          ],
        ),
      ),
    );
  }
}

// 功能
class GoodsTitleFunWidget extends StatelessWidget {

  GestureTapCallback? onTap;

  String ic;

  GoodsTitleFunWidget(this.ic,{this.onTap});

  @override
  Widget build(BuildContext context) {
    return InkWell(
      onTap: onTap,
      child: Container(
        alignment: Alignment.center,
        width: 36.sp,
        height: 36.sp,
        decoration:BoxDecoration(shape:BoxShape.circle,color: Color(0x33000000) ) ,
        child:Image.asset(assetPath(ic),width: 16.sp,height: 16.sp,color: Colors.white,),
      ),
    );
  }
}

// 功能
class GoodsFunWidget extends StatelessWidget {

  String name;
  String ic;

  GestureTapCallback? onTap;

  GoodsFunWidget(this.name, this.ic,{this.onTap});

  @override
  Widget build(BuildContext context) {
    return InkWell(
      onTap: onTap,
      child: Container(
        width: 40.sp,
        margin: EdgeInsets.fromLTRB(0, 0, 0.w, 20.sp),
        alignment: Alignment.center,
        child: Column(
          children: [
            Container(
              alignment: Alignment.center,
              width: 40.sp,
              height: 40.sp,
              margin: EdgeInsets.fromLTRB(0, 0, 0, 10.sp),
              decoration:BoxDecoration(shape:BoxShape.circle,color: Color(0x33000000) ) ,
              child:Image.asset(assetPath(ic),width: 20.sp,height: 20.sp,),
            ),
            Text(name,textAlign: TextAlign.center,style: TextStyle(fontSize: 13.sp,color: Colors.white),),
          ],
        ),
      ),
    );
  }
}


//商品信息-头部信息
class InfoHeadWidget extends StatelessWidget {

  GoodsDetailsBean? value;

  InfoHeadWidget(this.value);

  @override
  Widget build(BuildContext context) {
    return  Container(
      padding: EdgeInsets.fromLTRB(21.w, 24.sp, 21.w, 0.h),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          //商品名称
          Container(
              height: 42.sp,
              child: Text(value?.product?.name??"--",textAlign: TextAlign.left,style: TextStyle(color: Color(0xff2D3137),fontSize: 16.sp),maxLines: 2,softWrap:true ,overflow:TextOverflow.ellipsis,)),
          Padding(padding: EdgeInsets.fromLTRB(0, 0, 0, 10.sp)),
          //价格和标签
          Row(
            children: [
              PriceInfoDealWith(symbolSize: 16.sp, priceText: '${value?.product?.price??"--"}',priceSize: 28.sp,unitSize: 16.sp,unitText: '${value?.product?.unit??"--"}',isAskPriceFlag:value?.product?.isAskPriceFlag ,),
              Container(
                margin: EdgeInsets.fromLTRB(10.sp, 0, 0, 0),
                alignment: Alignment.center,
                decoration:ShapeDecoration(color: Color(0xffF2F2F2),shape: RoundedRectangleBorder(borderRadius: BorderRadius.all(Radius.circular(5.r)))),
                child: Text.rich(TextSpan(
                    children: [
                      WidgetSpan(child: Container(
                        alignment: Alignment.center,
                        padding: EdgeInsets.fromLTRB(8.sp, 4.sp, 8.sp, 4.sp),
                        decoration:ShapeDecoration(color: Color(0xffFF0041),shape: RoundedRectangleBorder(borderRadius: BorderRadius.all(Radius.circular(5.r)))),
                        child: Text("${value?.product?.labelName}",strutStyle: StrutStyle(height: 1),style: TextStyle(color: Colors.white,fontSize: 12.sp),),
                      )),
                      WidgetSpan(child: value?.product?.labelDescription==null? Text(""):Container(
                        alignment: Alignment.center,
                        padding: EdgeInsets.fromLTRB(10.sp, 4.sp, 10.sp, 4.sp),
                        child: Text("${value?.product?.labelDescription??""}",strutStyle: StrutStyle(height: 1),style: TextStyle(color: Color(0xff2D3137),fontSize: 12.sp),textAlign: TextAlign.center,),
                      )),
                    ]
                ),textAlign: TextAlign.center,),
              ),
              Expanded(
                child: Container(
                  alignment: Alignment.centerRight,
                  padding: EdgeInsets.zero,
                  child: Container(
                    alignment: Alignment.center,
                    width: 75.sp,
                    decoration:ShapeDecoration(color: Color(0xffFF8A2C),shape: RoundedRectangleBorder(borderRadius: BorderRadius.all(Radius.circular(5.r)))),
                    padding: EdgeInsets.fromLTRB(10.sp, 4.sp, 10.sp, 4.sp),
                    child: Text("立即询价",
                      style: TextStyle(color: Colors.white,fontSize: 12.sp),strutStyle: StrutStyle(height: 1),
                      textAlign: TextAlign.center,
                    ) // 关键属性 强制改为文字高度
                  ),
                ),
              )
            ],
          ),
          Padding(padding: EdgeInsets.fromLTRB(0, 0, 0, 15.sp)),
          Divider(height: 0.2.h,color:Color(0xffdddddd) ,),
          Padding(padding: EdgeInsets.fromLTRB(0, 0, 0, 25.sp)),
          //规格
          Row(
            crossAxisAlignment:CrossAxisAlignment.end ,
            children: [
              Container(
                width: 90.w,
                alignment: Alignment.centerLeft,
                child: Text("规格",textAlign: TextAlign.center,style: TextStyle(color: Color(0xff999999),fontSize: 14.sp),),
              ),
              Expanded(
                child: Container(
                  alignment: Alignment.centerLeft,
                  child: IntrinsicWidth(
                    child: Container(
                      color:  Color(0xffeeeeee),
                      padding: EdgeInsets.fromLTRB(4.w, 1.w, 4.w, 1.w),
                      alignment: Alignment.centerLeft,
                      child: Row(children: [
                        Text("${value?.sellerDescribed?.specification??""}",style: TextStyle(color: Color(0xff333333),fontSize: 12.sp),),
                        Padding(padding: EdgeInsets.fromLTRB(0, 0, 3.w, 0)),
                        Image.asset(assetPath("ic_expend_right.png"),height: 9.sp,fit: BoxFit.fitHeight,),
                      ],),
                    ),
                  ),
                ),
              )
            ],
          ),
          Padding(padding: EdgeInsets.fromLTRB(0, 0, 0, 15.sp)),
          //交货周期
          Row(
            crossAxisAlignment:CrossAxisAlignment.end ,
            children: [
              Container(
                width: 90.w,
                alignment: Alignment.centerLeft,
                margin: EdgeInsets.fromLTRB(0,10.sp, 0, 0),
                child: Text("交货周期",textAlign: TextAlign.center,style: TextStyle(color: Color(0xff999999),fontSize: 14.sp),),
              ),
              Expanded(
                child: Container(
                  alignment: Alignment.centerRight,
                  child: Container(
                    alignment: Alignment.centerLeft,
                    child: Text("${value?.sellerDescribed?.deliveryCycle??""}",style: TextStyle(color: Color(0xff333333),fontSize: 14.sp),),
                  ),
                ),
              )
            ],
          ),
          Padding(padding: EdgeInsets.fromLTRB(0, 0, 0, 30.sp)),
          Text("基础资料",style: TextStyle(fontSize: 16.sp,color: Color(0xff2D3137),fontWeight: FontWeight.w700),),
          Padding(padding: EdgeInsets.fromLTRB(0, 0, 0, 3.sp)),
          SizedBox(height: 2.sp,child: Divider(color:Color(0xffFF892B) ,thickness: 2.sp,),width: 60.sp,),
        ],
      ),
    );
  }
}


// 商品信息列表 item
class BasisInfoItem extends StatelessWidget {

  ProductAttributeValueList? productAttribute;
  BasisInfoItem(this.productAttribute);

  @override
  Widget build(BuildContext context) {
    return Container(
       alignment: Alignment.centerLeft,
       child: Column(
         crossAxisAlignment: CrossAxisAlignment.start,
         mainAxisAlignment: MainAxisAlignment.center,
         children: [
            Text("${productAttribute?.name??""}",style: TextStyle(color:Color(0xff999999),fontSize: 13.sp ),maxLines: 1,overflow: TextOverflow.ellipsis,softWrap: true,),
            Padding(padding: EdgeInsets.fromLTRB(0, 0, 0, 10.sp)),
            Text("${productAttribute?.value??""}",style: TextStyle(color:Color(0xff333333),fontSize: 13.sp ),maxLines: 1,overflow: TextOverflow.ellipsis,softWrap: true,),
         ],
       ),
    );
  }

}








